package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.pojo.PageBean;
import org.example.pojo.Result;
import org.example.pojo.User;
import org.example.pojo.UserDTO;
import org.example.service.UserService;
import org.example.util.JwtProperties;
import org.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 登录
     * @param userdto
     * @return
     */
    @PostMapping("/login")
    public Result login(UserDTO userdto) {
        // 判断是否为空
        if (userdto.getUsername() == null || userdto.getPassword() == null) {
            throw new RuntimeException("用户名或密码为空");
        }
        if (userdto.getType() == null){
            throw new RuntimeException("用户类型为空");
        }
        User loginUser = userService.login(userdto);
        // 登录成功，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", loginUser.getUsername());
        claims.put("id", loginUser.getId());
        String token = jwtUtil.genToken(claims, jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl());

        // 将生成的令牌保存到redis中，redis有效期1小时，与令牌失效期一致
        redisTemplate.opsForValue().set(token, token,1, TimeUnit.HOURS);

        return Result.success(token);
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/info")
    public Result info() {
        User user = userService.getInfo();
        return Result.success(user);
    }

    /**
     * 获取用户列表
     * @return
     */
    @GetMapping("/list")
    public Result list(Integer pageNum,Integer pageSize,String status,String inputName) {
        log.info("获取用户列表，页码：{}，页大小：{}，状态：{}，用户名：{}",pageNum,pageSize,status,inputName);
        PageBean<User> list = userService.list(pageNum, pageSize, status, inputName);
        return Result.success(list);
    }

    /**
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        log.info("添加用户，用户信息：{}",user);
        userService.add(user);
        return Result.success();
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        log.info("修改用户，用户信息：{}",user);
        userService.update(user);
        return Result.success();
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        log.info("删除用户，用户id：{}",id);
        userService.delete(id);
        return Result.success();
    }

    /**
     * 修改用户头像
     * @param avatarUrl
     * @return
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 修改密码
     * @param map
     * @return
     */
    @PutMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> map,@RequestHeader("Authorization") String token) {
        userService.updatePwd(map);
        // 密码修改成功，删除redis中的token
        redisTemplate.delete(token);
        return Result.success();
    }

    /**
     * 批量删除用户
     * @param ids
     * @return
     */
    @DeleteMapping("/batchDelete")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        userService.batchDelete(ids);
        return Result.success();
    }
}
